/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.ui.fileTransmiting;

import client.ui.fileTransmiting.removingTransmitedFile.RemoveProducer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import socketHandler.MessageSocketHandler;

/**
 *
 * @author lex
 */
public class ReciveFile extends TransmitedFile{
    public ReciveFile(String userName, File f, RemoveProducer remProd, long size) {
	super(userName, f, remProd, size);
    }

    
    @Override
    public void Start(Socket socket) {
        soc=socket;
	started=true;
        new Thread(new Runnable()
        {
            public void run()
            {
                jButton1.setEnabled(true);
                if (!f.exists()) try {
                    f.createNewFile();
                } catch (IOException ex) {}
                FileOutputStream fos=null;
                try {
                    fos=new FileOutputStream(f);
                } catch (FileNotFoundException ex) {}
		long readed_res=0;
                byte[] buf=new byte[buf_len];
                while(readed_res<size)
                {
                    int readed;
                    try {
                        readed = soc.getInputStream().read(buf);
			readed_res+=readed;
			if (readed<1) break;
                        fos.write(buf, 0, readed);
                    } catch (IOException ex) {break;}
		    setProgress((int)(readed_res*100/size));
                    synchronized(stop)
                    {
                        if (stop) break;
                    }
                }
		remProd.remove(nickName, f.getAbsolutePath());
		try {
		    fos.close();
		    soc.close();
		} catch (IOException ex) {}
            }
        }).start();
    }
    
}
